﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;

namespace AcademicAudit_JoelShuman
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

		private void Form1_Load(object sender, EventArgs e)
		{
			try
			{
				// Create a object to hold all the data in memory.
				theRecords = new MainRecords();

				// Read in all the student records on the disk.
				ReadStudentFiles();

				// Populate the combo box.
				PopulateComboBox();

				//theRecords.m_DefaultCourseList = CSVParser.ParseCourseCSV("../../DataFiles/GenericCourseData.csv");
				//// Create an XML Serialized Default Course List.
				//try
				//{
				//	XmlSerializer xx = new XmlSerializer(theRecords.m_DefaultCourseList.GetType());
				//	FileStream tempFss = new FileStream("../../DataFiles/DefaultCourse.xml", FileMode.OpenOrCreate, FileAccess.Write);
				//	StreamWriter tempWriter = new StreamWriter(tempFss);
				//	xx.Serialize(tempWriter, theRecords.m_DefaultCourseList);
				//	tempWriter.Close();
				//	tempFss.Close();
				//}
				//catch (Exception ex)
				//{
				//	Console.WriteLine(ex);
				//}

				// Read in the default course data into memory.  Used when a new student is created.
				XmlSerializer x = new XmlSerializer(typeof(List<Course>));
				FileStream tempFs = new FileStream("../../DataFiles/DefaultCourse.xml", FileMode.Open, FileAccess.Read);
				StreamReader tempReader = new StreamReader(tempFs);
				DefaultCourseList.DEFAULTCOURSELIST = (List<Course>)x.Deserialize(tempReader);
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex);
			}
		}

		// Save to disk.
		private void button1_Click(object sender, EventArgs e)
		{
			foreach (StudentRecord thisStudent in theRecords.m_AllStudents)
			{
				try
				{
					XmlSerializer x = new XmlSerializer(typeof(StudentRecord));
					FileStream tempFs = new FileStream(MainRecords.STUDENTDIR + thisStudent.m_FileName + ".xml", FileMode.Truncate, FileAccess.Write);
					StreamWriter tempS = new StreamWriter(tempFs);
					x.Serialize(tempS, thisStudent);
					tempS.Close();
					tempFs.Close();
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex);
				}
			}
		}

		MainRecords theRecords { get; set; }

		private void buttonAddStudent_Click(object sender, EventArgs e)
		{
			Form2 f = new Form2();
			if( f.ShowDialog() == DialogResult.OK )
			{
				StudentRecord tempStudent = new StudentRecord(f.textBoxFirstName.Text, f.textBoxLastName.Text);

				// Write an XML file for the student.
				try
				{
					XmlSerializer x = new XmlSerializer(typeof(StudentRecord));
					FileStream tempFs = new FileStream(MainRecords.STUDENTDIR + tempStudent.m_FileName + ".xml", FileMode.OpenOrCreate, FileAccess.Write);
					StreamWriter tempS = new StreamWriter(tempFs);
					x.Serialize(tempS, tempStudent);
					tempS.Close();
					tempFs.Close();

					if (!StudentIDNumbers.VerifyID(tempStudent.m_StudentID))
					{
						MessageBox.Show(tempStudent.m_StudentID + " is not a valid Student ID!\n\nUnable to create the student!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
						// Delete the file.
						File.Delete(MainRecords.STUDENTDIR + tempStudent.m_FileName + ".xml");
						StudentIDNumbers.FixIDFile();
						return;
					}
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex);
				}

				// Add the Student to the list in memory.
				theRecords.m_AllStudents.Add(tempStudent);
				
				// Add the item to the drop down box.
				comboBox1.Items.Add(tempStudent.m_FileName);

			}
		}

		private bool ReadStudentFiles()
		{
			var dirinfo = new DirectoryInfo(MainRecords.STUDENTDIR);
			var theFiles = dirinfo.GetFiles("*.xml", SearchOption.TopDirectoryOnly).ToList();

			foreach (var file in theFiles)
			{
				try
				{
					XmlSerializer x = new XmlSerializer(typeof(StudentRecord));
					FileStream tempFs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
					StreamReader tempS = new StreamReader(tempFs);
					theRecords.m_AllStudents.Add( (StudentRecord)x.Deserialize(tempS) );
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex);
					return false;
				}
			}
			return true;
		}

		private bool PopulateComboBox()
		{
			foreach (StudentRecord thisRecord in theRecords.m_AllStudents)
			{
				comboBox1.Items.Add(thisRecord.m_FileName);
			}
			return true;
		}
		
			//String selection = comboBox1.SelectedItem.ToString();
			//String [] splitList = selection.Split('_');
			//StudentRecord tempRecord = theRecords.GetStudentByID(splitList[0]);

			//// First Name
			//ListViewItem fName = new ListViewItem("First Name:");
			//fName.SubItems.Add(tempRecord.m_FirstName);
			//// Last Name
			//ListViewItem lName = new ListViewItem("Last Name:");
			//lName.SubItems.Add(tempRecord.m_LastName);
			//// ID
			//ListViewItem id = new ListViewItem("Student ID:");
			//id.SubItems.Add(tempRecord.m_StudentID);
			//// Core Course Completion %
			//ListViewItem coreP = new ListViewItem("Core Course Completion %:");
			//coreP.SubItems.Add(tempRecord.m_CoreCompletionPercentage.ToString());
			//// GenEd Course Completion %
			//ListViewItem genP = new ListViewItem("GenEd Course Completion %:");
			//genP.SubItems.Add(tempRecord.m_GenEdCompletionPercentage.ToString());
			//listViewStudentInfo.Items.AddRange( new ListViewItem[]{fName, lName, id, coreP, genP} );
		private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			String selection = comboBox1.SelectedItem.ToString();
			String [] splitList = selection.Split('_');

			UpdateStudentRecord(theRecords.GetStudentByID(splitList[0]));

			// Bind the student data to the grid view.
			BindingSource studentBindingSource = new BindingSource();
			studentBindingSource.DataSource = theRecords.GetStudentByID(splitList[0]);
			dataGridView1.DataSource = studentBindingSource;

			// Bind the student's course data to the grid view.
			BindingSource courseBindingSource = new BindingSource();
			courseBindingSource.DataSource = theRecords.GetStudentByID(splitList[0]).m_CourseList;
			dataGridView2.DataSource = courseBindingSource;
		}

		private void UpdateStudentRecord( StudentRecord theRecord )
		{
			// Lets Verify the ID as well.
			if (!StudentIDNumbers.VerifyID(theRecord.m_StudentID))
			{
				MessageBox.Show(theRecord.m_StudentID + " is not a valid Student ID!\nCould not update the student record.", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

			theRecord.m_FullName = theRecord.m_FirstName + " " + theRecord.m_LastName;
			theRecord.m_CoreCompletionPercentage = theRecord.CalculateCourseCompletionPercentage(CourseType.CORE);
			theRecord.m_GenEdCompletionPercentage = theRecord.CalculateCourseCompletionPercentage(CourseType.GENED);
			theRecord.m_FileName = theRecord.m_StudentID + "_" + theRecord.m_LastName + "_" + theRecord.m_FirstName;
			theRecord.m_GPA = theRecord.CalculateGPA();
		}

		private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{

		}

		private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			String selection = comboBox1.SelectedItem.ToString();
			String [] splitList = selection.Split('_');
			UpdateStudentRecord(theRecords.GetStudentByID(splitList[0]));
		}

		private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			String selection = comboBox1.SelectedItem.ToString();
			String[] splitList = selection.Split('_');
			UpdateStudentRecord(theRecords.GetStudentByID(splitList[0]));

			// Need to update dataGridView1 with the new data.
			UpdateValuesInStudentInfoGrid();
		}

		private void UpdateValuesInStudentInfoGrid()
		{
			int columnCount = dataGridView1.ColumnCount;
			int rowCount = dataGridView1.RowCount;
			for (int r = 0; r < rowCount; r++)
			{
				for (int c = 0; c < columnCount; c++)
					dataGridView1.UpdateCellValue(c, r);
			}
		}

		// Pad the Course ID with zeros and make the year four digits.
		private void dataGridView2_CellFormatting_1(object sender, DataGridViewCellFormattingEventArgs e)
		{
			if (e.Value != null && (e.ColumnIndex == mCourseIDDataGridViewTextBoxColumn.Index || e.ColumnIndex == myearDataGridViewTextBoxColumn.Index))
			{
				int val = (int)e.Value;
				e.Value = val.ToString("D4"); // apply formating here
				e.FormattingApplied = true;
			}
		}

		private void whereAreTheStudentFilesKeptToolStripMenuItem_Click(object sender, EventArgs e)
		{
			StreamWriter sw = null;
			FileStream fs = null;

			try
			{
				// Create a file showing where the files are kept.
				String fileName = "../../Datafiles/FileLocations.txt";
				fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
				sw = new StreamWriter(fs);

				sw.WriteLine("Student Record Files:\t" + Path.GetFullPath(MainRecords.STUDENTDIR));

                if (sw != null) sw.Close();
                if (fs != null) fs.Close();
                // Open the file.
                Process.Start(Path.GetFullPath(fileName));
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex);
			}
			finally
			{
				if (sw != null) sw.Close();
				if (fs != null) fs.Close();
			}			
		}

		private void changeLogToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Process.Start(Path.GetFullPath("../../ChangeLog.txt"));
		}
    }
}
